package me.macd.mindoc.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import me.macd.mindoc.dto.Result;
import me.macd.mindoc.model.BookResult;
import me.macd.mindoc.model.Books;
import me.macd.mindoc.model.MemberRelationshipResult;
import me.macd.mindoc.service.BookService;
import me.macd.mindoc.service.MemberRelationshipService;
import me.macd.mindoc.util.Page;
import me.macd.mindoc.util.Pagination;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @program: mindoc
 * @description: ${description}
 * @author: 2018-09-24
 * @create: 2018-09-24 10:05
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private MemberRelationshipService memberRelationshipService;

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
    public String index(@RequestParam(value = "page", defaultValue = "1") int pageIndex, Model model) {
        model.addAllAttributes(Common.map("BookController", "Index"));
        Page<BookResult> page = bookService.findToPager(pageIndex, 10, Common.memberId());

        if (page.getTotalCount() > 0) {
            Pagination pager = new Pagination(request, page.getTotalCount(), 10);
            model.addAttribute("PageHtml", pager.Pages());
        } else {
            model.addAttribute("PageHtml", "");
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            model.addAttribute("Result", mapper.writeValueAsString(page.getItems()));
        } catch (JsonProcessingException e) {
            model.addAttribute("Result", "[]");
            e.printStackTrace();
        }

        return "book/index";
    }

    @RequestMapping(value = "/{key}/dashboard", method = RequestMethod.GET)
    public String dashboard(@PathVariable("key") String key, Model model) {
        model.addAllAttributes(Common.map("BookController", "Dashboard"));

        BookResult bookResult = bookService.findByIdentify(key, Common.memberId());
        model.addAttribute("Description", bookResult.getDescription());
        model.addAttribute("Model", bookResult);
        return "book/dashboard";
    }

    @RequestMapping(value = "/{key}/users", method = RequestMethod.GET)
    public String users(@PathVariable("key") String key, @RequestParam(value = "page", defaultValue = "1") int pageIndex, Model model) {
        model.addAllAttributes(Common.map("BookController", "Users"));

        BookResult bookResult = bookService.findByIdentify(key, Common.memberId());
        model.addAttribute("Model", bookResult);

        Page<MemberRelationshipResult> page = memberRelationshipService.findForUsersByBookId(bookResult.getBookId(), pageIndex, 15);

        if (page.getTotalCount()>0) {
            Pagination pagination = new Pagination(request, page.getTotalCount(), 15);
            model.addAttribute("PageHtml", pagination.Pages());
        } else {
            model.addAttribute("PageHtml", "");
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            model.addAttribute("Result", mapper.writeValueAsString(page.getItems()));
        } catch (JsonProcessingException e) {
            model.addAttribute("Result", "[]");
            e.printStackTrace();
        }

        return "book/users";
    }

    @RequestMapping(value = "/{key}/setting", method = RequestMethod.GET)
    public String setting(@PathVariable("key") String key, Model model) {
        model.addAllAttributes(Common.map("BookController", "Setting"));
        BookResult bookResult = bookService.findByIdentify(key, Common.memberId());
        model.addAttribute("Model", bookResult);

        return "book/setting";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Result create(@RequestParam(value = "book_name", defaultValue = "")String bookName,
                         @RequestParam(value = "identify", defaultValue = "")String identify,
                         @RequestParam(value = "description", defaultValue = "")String description,
                         @RequestParam(value = "privately_owned", defaultValue = "0")int privatelyOwned,
                         @RequestParam(value = "comment_status", defaultValue = "")String commentStatus) {
        if (StringUtils.isBlank(bookName)) {
            return new Result(6001, "项目名称不能为空");
        }
        if (StringUtils.isBlank(identify)) {
            return new Result(6002, "项目标识不能为空");
        }
        if (!Pattern.matches("^[a-z]+[a-zA-Z0-9_\\-]*$", identify)) {
            return new Result(6003, "项目标识只能包含小写字母、数字，以及“-”和“_”符号,并且只能小写字母开头");
        }
        if (identify.length()>50) {
            return new Result(6004, "文档标识不能超过50字");
        }
        if (description.length()>500) {
            return new Result(6004, "项目描述不能大于500字");
        }
        if (privatelyOwned != 0 && privatelyOwned != 1) {
            privatelyOwned = 1;
        }
        if (!"open".equals(commentStatus) &&
                !"closed".equals(commentStatus) &&
                !"group_only".equals(commentStatus) &&
                !"registered_only".equals(commentStatus)) {
            commentStatus = "closed";
        }

        if (bookService.existByIdentify(identify)) {
            return new Result(6006, "项目标识已存在");
        }

        Books book = new Books();
        book.setCover("/images/book.jpg");
        book.setBookName(bookName);
        book.setDescription(description);
        book.setCommentCount(0);
        book.setPrivatelyOwned(privatelyOwned);
        book.setCommentStatus(commentStatus);
        book.setIdentify(identify);
        book.setDocCount(0);
        book.setMemberId(Common.memberId());
        book.setVersion(new Date().getTime()/1000);
        book.setIsEnableShare(0);
        book.setIsUseFirstDocument(1);
        book.setIsDownload(1);
        book.setAutoSave(0);
        book.setAutoRelease(0);
        book.setEditor("markdown");
        book.setTheme("default");
        book.setOrderIndex(0);
        book.setPublisher("");
        book.setLabel("");
        book.setStatus(0);
        book.setCreateTime(new Date());
        book.setModifyTime(new Date());
        book.setHistoryCount(0);

        bookService.insert(book);

        BookResult bookResult = bookService.findByIdentify(identify, Common.memberId());
        return new Result(0, "ok", bookResult);
    }
}
